import java.util.Arrays;

public class Test {
    public static void quickSort(int[] arr) {
        quick(arr,0,arr.length-1);
    }

    private static void quick(int[] arr, int start, int end) {
        if (start >= end) return;
        //减少函数栈帧
        if (end-start+1 <= 7) {
            insertSortOfRange(arr,start,end);
            return;
        }
        //三数取中
        int midIndex = findMid(arr,start,end);
        swap(arr,midIndex,start);

        int center = partitionHole(arr,start,end);

        quick(arr,start,center-1);
        quick(arr,center+1,end);
    }

    private static void insertSortOfRange(int[] arr, int start, int end) {
        for (int i = start+1; i <= end; i++) {
            int tmp = arr[i];
            int j = i-1;
            for (; j >= start; j--) {
                if (tmp < arr[j]) {
                    arr[j+1] = arr[j];
                }else {
                    break;
                }
            }
            arr[j+1] = tmp;
        }
    }

    private static int findMid(int[] arr, int left, int right) {
        int mid = (left+right)/2;
        if (arr[left] > arr[right]) {
            if (arr[mid] > arr[left]) {
                return left;
            }else if (arr[right] > arr[mid]) {
                return right;
            }else {
                return mid;
            }
        }else {
            if (arr[mid] > arr[right]) {
                return right;
            } else if (arr[left] > arr[mid]) {
                return left;
            }else {
                return left;
            }
        }
    }

    private static int partitionHole(int[] arr, int left, int right) {
        int tmp = arr[left];
        while (left != right) {
            while (left != right && arr[right] >= tmp) {
                right--;
            }
            arr[left] = arr[right];
            while (left != right && arr[left] <= tmp) {
                left++;
            }
            arr[right] = arr[left];
        }
        arr[left] = tmp;
        return left;
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {23,122,0,12,5657,12,48,-14,2,7,2,19,24,26,10,88,66,16};
        quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}